#include "lichenparsepacket.h"
#include <QDebug>
#include "convert.h"
#include "moduleelectronicscaledefine.h"
#include "moduleelectronicscalecmdid.h"

LiChenParsePacket::LiChenParsePacket(electronicscale::ElectronicScaleParam &param, LiChenProtocolData &data, QObject *parent)
    : BaseParsePacket (data, parent)
{
    m_param = &param;
}

LiChenParsePacket::~LiChenParsePacket()
{

}

void LiChenParsePacket::parse()
{
    QByteArray &packet = m_d->m_rxPacket.buffer;

    bool ok = false;
    double value = packet.mid(3, 8).simplified().toDouble(&ok);
    if (!ok)
    {
        m_d->m_rxPacket.clear();
        return;
    }

    bool isPositive = packet.at(2) == '+' ? true : false;
    if (!isPositive)
        value *= -1;

    electronicscale::Sample sample;
    sample.time = m_d->m_rxPacket.timestamp;
    sample.weight.value = value;
    QByteArray unit = packet.mid(11, 3).simplified();
    if (unit == "g")
    {
        sample.weight.unit = electronicscale::WeightUnit_g;
        m_param->samples << sample;
//        qDebug() << "sample = " << sample.weight.value << unit;

        QVariant var;
        var.setValue(sample);
        emit parseCompleted(electronicscale::ElectronicScaleCmdID_Weight, var);
    }
    else if (unit == "ct")
    {
        sample.weight.unit = electronicscale::WeightUnit_ct;
        m_param->samples << sample;

        QVariant var;
        var.setValue(sample);
        emit parseCompleted(electronicscale::ElectronicScaleCmdID_Weight, var);
    }

    m_d->m_rxPacket.clear();
}
